const { Advice, User } = require('../db')

exports.sendAdvice = async (req, res) => {
    const { content } = req.body
    const { id: userId } = req.user
    try {
        const user = await User.findByPk(userId)
        if (!user) {
            return res.status(404).json({ message: 'User not found' })
        }
        const newAdvice = await Advice.create({ content, userId, date: new Date() })
        res.status(200).json({ status: 200, message: '提供意见成功' })
    } catch (error) {
        console.log(error);

        res.status(500).json({ message: error.message })
    }
}

// 分页获得意见
exports.getAdvice = async (req, res) => {
    const { page = 1, pageSize = 10, ifAll } = req.body
    const { id: userId } = req.user
    try {
        if (ifAll) {
            const advice = await Advice.findAndCountAll({
                offset: (page - 1) * pageSize,
                limit: pageSize,
                include: [{
                    model: User,
                    // attributes: ['name', 'jobNumber']
                    attributes: ['username']
                }],
                order: [['date', 'DESC']]
            })
            res.status(200).json({ status: 200, data: advice.rows, total: advice.count })
        } else {
            const advice = await Advice.findAndCountAll({
                where: { userId },
                offset: (page - 1) * pageSize,
                limit: pageSize,
                include: [{
                    model: User,
                    // attributes: ['name', 'jobNumber']
                    attributes: ['username']
                }],
                order: [['date', 'DESC']]
            })
            res.status(200).json({ status: 200, data: advice.rows, total: advice.count })
        }
    } catch (error) {
        res.status(500).json({ status: 500, message: error.message })
    }
}

// 删除意见
exports.deleteAdvice = async (req, res) => {
    const { id } = req.body;
    try {
        const advice = await Advice.findByPk(id)
        if (!advice) {
            return res.status(404).json({ message: '意见不存在' })
        }
        await advice.destroy()
        res.status(200).json({ status: 200, message: '删除意见成功' })
    } catch (error) {
        res.status(500).json({ status: 500, message: error.message })
    }
}